﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace MetaDemo.Forms
{
    public partial class CompileCodeForm : Form
    {

        public static CompileCodeForm Get()
        {
            return new CompileCodeForm();
        }

        public static CompileCodeForm Get(Object o)
        {
            var form = Get();
            form.Context = o;
            return form;
        }


        private Assembly compiledAssembly;

        private Object context = null;
        public Object Context { get { return context; } set {
                context = value;
                lblContextValue.Text = context.GetType().Name;
            }
        }

        public CompileCodeForm()
        {
            InitializeComponent();

            btnCompile.Click += new EventHandler(btnCompile_Click);
            btnExecute.Click += new EventHandler(btnExecute_Click);
        }



        #region handler

        void btnCompile_Click(object sender, EventArgs e)
        {
            try
            {
                compiledAssembly = CompileHelper.createAssemblyViaCSharp(txtCode.Text, context);
                if (null == compiledAssembly)
                    throw new CompileException();

                btnExecute.Enabled = true;
            }
            catch (CompileException exc)
            {
                btnExecute.Enabled = false;
                compiledAssembly = null;

                MessageBox.Show("CompileErrors: " + exc.Errors.Count);
                foreach (String errormsg in exc.Errors)
                {
                    Console.WriteLine(errormsg);
                }
            }
        }

        void btnExecute_Click(object sender, EventArgs e)
        {
            try
            {
                compiledAssembly.EntryPoint.Invoke(null, null);
            }
            catch (Exception exc)
            {
                MessageBox.Show("An error has occurred: " + exc.Message);
            }
        }

        #endregion
    }
}
